import axios from 'axios'
import { ElMessage } from 'element-plus'

const API = axios.create({ baseURL: '/api', timeout: 600000, responseType: 'json', headers: { 'Content-Type': 'application/json' } })

// request拦截器
API.interceptors.request.use(
  (config) => {
    // ------ 时间戳
    config.params = { _t: new Date().getTime(), ...config.params }

    // config.headers = { ...config.headers, Authorization: localStorage.getItem('token') }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 返回状态判断(添加响应拦截器) 每条请求信息都会走到这里
API.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      return response.data
    } else {
      ElMessage.error('服务器返回结果错误,请联系客服！')
      return Promise.reject()
    }
  },
  () => {
    ElMessage.error('本地网络连接失败、请检查网络是否正常！')
    return Promise.reject()
  },
)

export default API
